<template>
  <div id="cpn-upload-field" :style="{ '--width': width, '--height': height }">
    <el-upload class="img-uploader" :action="action" :show-file-list="false" :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="imgData" :src="baseImgDownLoadUrl + imgData" class="img">
      <template v-else>
        <i v-if="$chy.isEmpty(placeholder)" class="el-icon-plus img-uploader-icon"></i>
        <div class="placeholder font4 f12" v-else>{{ placeholder }}</div>
      </template>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'upload-field',
  model: {
    prop: 'value',
    event: 'upload'
  },
  props: {
    value: {
      typeof: String,
      default: ''
    },
    // 自定义宽高
    width: {
      type: String,
      default: '120px'
    },
    height: {
      type: String,
      default: '120px'
    },
    action: {
      typeof: String,
      default: `${process.env.NODE_ENV === 'development' ? '/api' : process.env.VUE_APP_BASE_API}/common/upload/img`
    },
    placeholder: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imgData: ''
    }
  },
  created() {
    this.imgData = this.value
  },
  watch: {
    // defaultImg(newVal) {
    //   this.imgData = newVal
    // }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log('res', res, file)
      // this.imgData = URL.createObjectURL(file.raw)
      this.imgData = res.data.url
      this.$emit('upload', res.data.url)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    }
  }

}
</script>

<style lang="scss" scoped>
#cpn-upload-field {
  ::v-deep .img-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: $themeColor1 !important;
    }
  }
  .placeholder {
    width: var(--width);
    height: var(--height);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  ::v-deep .img-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: var(--width);
    height: var(--height);
    line-height: var(--height);
    text-align: center;
  }

  .img {
    width: var(--width);
    height: var(--height);
    display: block;
  }
}
</style>